package com.zhhtech.zhh.ui.activity.main

import android.view.View
import com.alibaba.fastjson.JSON
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.zhhtech.zhh.R
import com.zhhtech.zhh.bean.FuZhai
import com.zhhtech.zhh.databinding.ActivityFuzhaiBinding
import com.zhhtech.zhh.ui.base.BaseActivity
import com.zhhtech.zhh.ui.dialog.showAlertDialog
import com.zhhtech.zhh.ui.ext.toColor
import com.zhhtech.zhh.ui.ext.toastMessageLong
import com.zhhtech.zhh.ui.ext.value
import com.zhhtech.zhh.ui.helper.mohsi.MoshiUtils
import com.zhhtech.zhh.ui.utils.SPUtils
import com.zhhtech.zhh.utils.StringUtils

class FuZhaiAddActivity : BaseActivity<ActivityFuzhaiBinding>() {
    private lateinit var fzsjPicker: CardDatePickerDialog
    private lateinit var hzsjPicker: CardDatePickerDialog
    override fun initView() {
        fzsjPicker = CardDatePickerDialog.builder(this)
            .setTitle("负债时间选择")
            .setThemeColor(R.color.main_color.toColor())
            .setOnChoose("选择") {
                vb.etFzsj.text = StringUtils.conversionTime(it)
            }
            .setOnCancel("关闭")
            .build()
        hzsjPicker = CardDatePickerDialog.builder(this)
            .setTitle("还债时间选择")
            .setThemeColor(R.color.main_color.toColor())
            .setOnChoose("选择") {
                vb.etHzsj.text = StringUtils.conversionTime(it)
            }
            .setOnCancel("关闭")
            .build()
        bindViewClick(vb.buttonSave, vb.etFzsj, vb.etHzsj)
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.etFzsj -> fzsjPicker.show()
            vb.etHzsj -> hzsjPicker.show()
            vb.buttonSave -> {
                val fuZhai = FuZhai()
                fuZhai.pingtai = vb.etPt.value
                fuZhai.jine = vb.etJe.value
                fuZhai.fzsj = vb.etFzsj.value
                fuZhai.hzsj = vb.etHzsj.value
                if (fuZhai.pingtai.isBlank() ||
                    fuZhai.jine.isBlank() ||
                    fuZhai.fzsj.isBlank() ||
                    fuZhai.hzsj.isBlank()
                ) {
                    "请填写完整".toastMessageLong()
                    return
                }
                showAlertDialog {
                    message("确定保存吗？")
                    negativeButton { }
                    positiveButton {
                        val fuzhais =
                            JSON.parseArray(
                                SPUtils.getString("fuzhai", "[]").ifBlank { "[]" },
                                FuZhai::class.java
                            )
                                ?: mutableListOf()
                        fuzhais.add(fuZhai)
                        SPUtils.put("fuzhai", MoshiUtils.toJSONString(fuzhais))
                        setResult(RESULT_OK)
                        finish()
                    }
                }
            }
        }
    }
}